package org.truenewx.tnxjee.core.version;

import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.truenewx.tnxjee.core.Strings;
import org.truenewx.tnxjee.core.util.TemporalUtil;

/**
 * Maven版本号读取器
 *
 * @author jianglei
 */
@Component
@PropertySource("classpath:maven.properties")
public class MavenVersionReader extends AbstractVersionReader {

    @Override
    protected String readFullVersion(ApplicationContext context) {
        Environment environment = context.getEnvironment();
        String version = environment.getProperty("project.version");
        if (version != null) {
            String pattern = environment.getProperty("project.build.timestamp.pattern");
            if (StringUtils.isNotBlank(pattern)) {
                int index = version.lastIndexOf(Strings.DOT);
                if (index > 0) {
                    String prefix = version.substring(0, index + 1);
                    String timestamp = version.substring(index + 1);
                    LocalDateTime dateTime = TemporalUtil.parse(LocalDateTime.class, timestamp, pattern);
                    dateTime = TemporalUtil.utcToDefaultZone(dateTime);
                    if (dateTime != null) {
                        version = prefix + TemporalUtil.format(dateTime, pattern);
                    }
                }
            }
        }
        return version;
    }

}
